<?php
/**
 * 创建人 : Forpastime
 * 创建时间: 2022/7/7 14:39
 * 个人主页 : http://forpastime.com
 */
declare(strict_types=1);

namespace App\Controller;

use http\Client\Response;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Hyperf\Utils\Arr;

/**
 * @AutoController()
 */
class UserController extends AbstractController
{
    // Hyperf 会自动为此方法生成一个 /user/index 的路由，允许通过 GET 或 POST 方式请求
    public function index(RequestInterface $request)
    {
        // 从请求中获得 id 参数
        $id = $request->input('id', 1);
        return (string)$id;
    }

    public function getInfo()
    {
        Db::enableQueryLog();

        //执行原生sql
        //$res = Db::select('select * from for_user;');

        //通过id查找指定字段
        //$res = Db::table('user')->find('2',['name','sex']);

        //通过select指定字段
        //$res = Db::table('user')->select(['name','sex'])->find(2);

        //链接表查询
        /*
        $res = Db::table('user')
            ->leftJoin('userInfo','user.id','=','userInfo.user_id')
            ->select('user.name','userInfo.address')
            ->get();
        */

        //通过where条件查询
        //$res = Db::table('user')->where('id','>',1)->get();

        //多个where条件
        $thisMonth = strtotime('-1 month');
        $res = Db::table('user')
            ->where([['sex','=',1],['create_time','>',$thisMonth]])
            //->whereTime('create_time','>',$thisMonth) //此方法不可用：lastSql":{"query":"select * from `for_user` where (`sex` = ?) and time(`create_time`) > ? order by `create_time` desc limit 2","bindings":[1,"2022-06"]
            ->limit(2)
            ->orderBy('create_time','desc')
            //->orderByDesc('create_time')
            ->get();
        return [
            'code'=>1,
            'data'=>$res,
            'thisMonth'=>$thisMonth,
            'lastSql'=>Arr::last(Db::getQueryLog())
        ];
    }

    /**
     * 注册
     * @return array
     */
    public function register()
    {
        $res = Db::table('user')
            ->insertGetId([
                'mobile'=>'18428339028',
                'name'=>'For',
                'sex'=>1,
                'create_time'=>time()
            ]);
        return [
            'code'=>1,
            'data'=>$res
        ];
    }

    public function setMobile(RequestInterface $request,ResponseInterface $response)
    {
        if(!$request->has(['id','mobile'])){
            $this->error('参数异常');
        }
        //$mobile = $request->input('mobile');
        //$param = $request->all();
        $param = $request->query();

        if(!empty($param)){
            $res = Db::table('user')->where('id',$param['id'])->update(['mobile'=>$param['mobile']]);
            return [
                'code'=>1,
                'data'=>$res
            ];
        }
    }
}